<template>
  <page-view class="page-view" :title="false" style="user-select: none">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item>申请管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">

        <a-tabs v-model="tabIndex" animated type="card">
          <a-tab-pane v-for="(tab, index) in tabList" :key="index" :tab="tab.name">
            <div class="filter">
              <a-form>
                <a-row>

                  <a-col :lg="8" :md="12" :sm="24">
                    <a-form-item label="单据编号" v-bind="formItemLayout">
                      <a-input v-model="tempQueryParam[index].sn" placeholder="请输入" />
                    </a-form-item>
                  </a-col>

                  <a-col :lg="8" :md="12" :sm="24">
                    <a-form-item label="发起日期" v-bind="formItemLayout">
                      <a-date-picker v-model="tempQueryParam[index].createdTime" placeholder="请选择" />
                    </a-form-item>
                  </a-col>

                  <a-col v-if="tabIndex < 3" :lg="8" :md="12" :sm="24">
                    <a-form-item :label="`${tab.name.substr(0, 2)}状态`" v-bind="formItemLayout">
                      <a-select v-model="tempQueryParam[index].status" placeholder="请选择">
                        <a-select-option
                          v-for="sItem in ([...statusList].filter(i => statusFilter[tabIndex].name.includes(i.name)))"
                          :key="sItem.name"
                          :value="sItem.value"
                        >{{ sItem.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>

                  <a-col :lg="8" :md="12" :sm="24">
                    <a-form-item :label="index > 1 ? '报修类型' : `${tab.name.substr(0, 2)}部门`" v-bind="formItemLayout">
                      <a-select v-model="tempQueryParam[index][tab.key4]" placeholder="请选择">
                        <a-select-option
                          v-for="sItem in (index > 1 ? attrList : deptList)"
                          :key="sItem.deptId"
                          :value="sItem.deptId"
                        >{{ sItem.deptName }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>

                  <a-col :lg="8" :md="12" :sm="24">
                    <a-form-item :label="index > 1 ? '报修地点' : '审批人'" v-bind="formItemLayout">
                      <a-input v-model="tempQueryParam[index].approverName" placeholder="请输入" />
                    </a-form-item>
                  </a-col>

                  <a-col :lg="8" :sm="12" :xs="24">
                    <div class="btn-container align-right">
                      <a-button type="primary" @click="handleSearch(index)">查询</a-button>
                      <a-button @click="reset(index)">重置</a-button>
                      <a-button :loading="sending" @click="handleExport(index)">导出报表</a-button>
                    </div>
                  </a-col>

                </a-row>
              </a-form>
            </div>

            <s-table
              :ref="`table${index}`"
              class="s-table"
              bordered
              row-key="id"
              :locale="{ emptyText: '暂无数据' }"
              :show-pagination="false"
              :columns="[columns0, columns1, columns2][index]"
              :data="loadData"
              :alert="false"
            >
              <template slot="action" slot-scope="item">
                <div class="action-container">
                  <span v-if="index === 2" class="success-link" @click="checkPDF(item, index)">查看报修单</span>
                  <span v-else class="success-link" @click="checkPDF(item, index)">查看申请单</span>
                </div>
              </template>
            </s-table>

            <!-- 分页器 -->
            <div class="pagination-container">
              <a-pagination
                :page-size="queryParam[index].pageSize"
                :show-total="total => `共 ${total} 条记录 第 ${queryParam[index].pageNum} / ${Math.ceil(total / queryParam[index].pageSize)} 页`"
                :current="queryParam[index].pageNum"
                :total="[count0, count1, count2][index]"
                hide-on-single-page
                show-quick-jumper
                @change="handlePage"
              />
            </div>
          </a-tab-pane>

          <!-- 审批设置 -->
          <a-tab-pane :key="3" tab="审批设置">
            <a-tabs v-model="settingTabIndex" class="tabs-col" tab-position="left" animated type="card">
              <a-tab-pane v-for="(tab, k) in ['申购审批设置', '申领审批设置']" :key="k" :tab="tab">
                <a-form>
                  <a-row>
                    <a-col :span="12">
                      <a-form-item label="审批类型" v-bind="formItemLayout">
                        <a-radio-group
                          v-model="settingData.status"
                          :options="[{ value: 0, label: '上级审批 '}, { value: 1, label: '固定人审批' }]"
                        />
                      </a-form-item>
                    </a-col>
                  </a-row>
                  <a-row v-for="(pItem, index) in settingData.personList" :key="index">
                    <a-col :span="12">
                      <a-form-item :label="`审批人${index + 1}`" v-bind="formItemLayout">
                        <a-col :span="18">
                          <a-input
                            :value="$get(teacherMaps, `${pItem.userId}.name`)"
                            read-only
                            placeholder="请输入"
                            @click="handleSelect(pItem.userId, index)"
                          />
                        </a-col>
                        <a-col :span="4">
                          <span class="danger-link" @click="handleDel(index)">删除</span>
                        </a-col>
                      </a-form-item>
                    </a-col>
                  </a-row>

                  <a-row>
                    <a-col :span="10">
                      <a-col :span="6" />
                      <a-col v-if="settingData.status > 0" :span="16" class="primary-link" style="margin-bottom: 20px" @click="handleSelect()">添加审批人</a-col>
                    </a-col>
                  </a-row>

                  <a-row>
                    <a-col :span="10">
                      <a-col :span="6" />
                      <a-col :span="16">
                        <a-button class="primary-btn" :loading="sending" @click="handleUpdate">确定</a-button>
                        <a-button @click="handleReset">取消</a-button>
                      </a-col>
                    </a-col>
                  </a-row>
                </a-form>
              </a-tab-pane>

              <a-tab-pane :key="2" tab="报修审批设置">
                <a-form>
                  <a-row>
                    <a-col :span="10">
                      <a-form-item label="第一审批人" v-bind="formItemLayout">
                        <teacher-select v-model="settingData.userData.userId" placeholder="请选择审批人" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                  <a-row>
                    <a-col :span="10">
                      <a-col :span="6" />
                      <a-col :span="16">
                        <a-button class="primary-btn" :loading="sending" @click="handleUpdate">确定</a-button>
                        <a-button @click="handleReset">取消</a-button>
                      </a-col>
                    </a-col>
                  </a-row>
                </a-form>
              </a-tab-pane>
            </a-tabs>
          </a-tab-pane>
          <!-- 审批设置 end -->

        </a-tabs>

      </a-spin>
    </a-card>

    <a-modal
      title="选择审批人"
      :visible="showSelect"
      centered
      @ok="handleOk"
      @cancel="showSelect = false"
    >
      <a-form-item label="部门" v-bind="formItemLayout">
        <a-select v-model="tempDept" placeholder="选择部门" style="width: 100%" allow-clear>
          <a-select-option
            v-for="sItem in deptList"
            :key="sItem.deptId"
            :value="sItem.deptId"
          >{{ sItem.deptName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item required label="审批人" v-bind="formItemLayout">
        <teacher-select
          v-model="tempUserId"
          :filter-function="i => i.departmentId === (tempDept || i.departmentId)"
          :disabled="item => settingData.personList.map(i => i.userId).includes(item.userId)"
          placeholder="请选择审批人"
        />
      </a-form-item>
    </a-modal>

    <PDFModal
      :url="url"
      :file-name="fileName"
      :visible="showPDF"
      :title="modalTitle"
      :extra-text="modalText"
      @cancel="showPDF = false"
    />

  </page-view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { PageView, STable, PDFModal, TeacherSelect, ExportModal } from '@/components'

const statusList = [
  { value: '1', name: '待审批' },
  { value: '2', name: '不通过' },
  { value: '3', name: '待指派' },
  { value: '4', name: '待维修' },
  { value: '5', name: '处理中' },
  { value: '7', name: '待确认' },
  { value: '4,6,7,8,9', name: '已完成' },
  { value: '10,11', name: '已撤销' }
]
const statusFilter = [
  { name: '待审批,不通过,已完成,已撤销', value: '1,2,4,8,10,11' },
  { name: '待审批,不通过,已完成,已撤销', value: '1,2,4,6,8,9,10,11' },
  { name: '待指派,待维修,处理中,待确认,已完成,已撤销', value: '3,4,5,7,8,10' }
]
const statusMaps = {
  1: '待审批',
  2: '不通过',
  3: '待指派',
  4: '已完成',
  5: '处理中',
  6: '已完成',
  7: '已完成',
  8: '已完成',
  9: '已完成',
  10: '已撤销',
  11: '已撤销'
}
const attrList = [
  { deptId: '水电', deptName: '水电' },
  { deptId: '木工', deptName: '木工' },
  { deptId: '空调', deptName: '空调' }
]

export default {
  name: 'Apply',
  components: { PageView, STable, PDFModal, TeacherSelect, ExportModal },
  inject: ['formItemLayout'],

  async fetch ({ app, store }) {
    const list = []
    const { $get } = store
    if (!store.$get(store, 'state.basic.teacherList.length')) app.$teacherListFunc()
    else app.$teacherListFunc()
    if (!$get(store, 'state.basic.deptList.length')) list.push({ fn: app.$departmentListFunc })
    await app.$requestList(list)
  },

  data () {
    return {
      sending: false,
      tabIndex: 0,
      settingTabIndex: 0,

      showExport: false,

      url: '',
      fileName: '',
      showPDF: false,
      modalTitle: '',
      modalText: '',

      statusList,
      statusFilter,
      attrList,

      settingData: {
        status: 0,
        personList: [],
        deleteList: [],
        userData: { userId: undefined }
      },
      oldSettingData: {},
      tempUserId: undefined,
      tempDept: undefined,
      tempIndex: -1,
      showSelect: false,

      tempQueryParam: [
        { sn: undefined, createdTime: undefined, status: undefined, deptId: undefined, approverName: undefined },
        { sn: undefined, createdTime: undefined, status: undefined, deptId: undefined, approverName: undefined },
        { sn: undefined, createdTime: undefined, status: undefined, attr: undefined, location: undefined }
      ],

      tabList: [
        { name: '申购记录', key4: 'deptId', key5: 'userName' },
        { name: '申领记录', key4: 'deptId', key5: 'userName' },
        { name: '报修记录', key4: 'attr', key5: 'location' }
      ],

      count0: 0,
      columns0: [
        { title: '单据编号', align: 'center', dataIndex: 'sn' },
        { title: '发起日期', align: 'center', dataIndex: 'createdDate' },
        { title: '申购部门', align: 'center', dataIndex: 'deptName' },
        { title: '申购人', align: 'center', dataIndex: 'userName' },
        { title: '申购总额(元)', align: 'center', dataIndex: 'amount' },
        { title: '状态', align: 'center', dataIndex: 'statusName' },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' }}
      ],

      count1: 0,
      columns1: [
        { title: '单据编号', align: 'center', dataIndex: 'sn' },
        { title: '发起日期', align: 'center', dataIndex: 'createdDate' },
        { title: '申领部门', align: 'center', dataIndex: 'deptName' },
        { title: '申领人', align: 'center', dataIndex: 'userName' },
        { title: '物品总数', align: 'center', dataIndex: 'quantity' },
        { title: '申领状态', align: 'center', dataIndex: 'statusName' },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' }}
      ],

      count2: 0,
      columns2: [
        { title: '单据编号', align: 'center', dataIndex: 'sn' },
        { title: '发起日期', align: 'center', dataIndex: 'createdDate' },
        { title: '申请人', align: 'center', dataIndex: 'userName' },
        { title: '报修地点', align: 'center', dataIndex: 'location' },
        { title: '报修类型', align: 'center', dataIndex: 'attr' },
        { title: '物品总数', align: 'center', dataIndex: 'quantity' },
        { title: '报修状态', align: 'center', dataIndex: 'statusName' },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' }}
      ]
    }
  },

  computed: {
    ...mapState({
      deptList: state => state.basic.deptList,
      deptMaps: state => state.basic.deptMaps,
      teacherMaps: state => state.basic.teacherMaps,
      queryParam: state => state.property.applyQueryParam
    })
  },

  watch: {
    $route (t) {
      if (t.name === 'property-apply') this.refresh(this.tabIndex)
    },

    tabIndex (index) {
      this.refresh(index)
    },

    settingTabIndex (index) {
      this.getSettings(index)
    },

    'settingData.status' (status) {
      const { settingData, oldSettingData } = this
      if (!status) settingData.personList.splice(0)
      else if (!settingData.personList.length) Object.assign(settingData.personList, oldSettingData.personList)
    },

    queryParam: {
      handler (list) {
        list.forEach((obj, index) => {
          const target = this.tempQueryParam[index]
          for (const key in target) {
            target[key] = obj[key]
          }
        })
        this.$forceUpdate()
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    ...mapActions('property', ['setQueryParam']),

    loadData () {
      const { tabIndex, handleParams, $axios, $get, $moment } = this
      const loadRes = { data: [] }
      const params = handleParams()

      return $axios.post('api/assetsApply/query', params).then(res => {
        loadRes.data = $get(res, 'data.data.dataList', []).map(item => {
          const data = { createdDate: item.createdTime ? $moment(item.createdTime).format('YYYY.MM.DD') : '-' }
          if (tabIndex === 2) {
            if (item.status === 4) data.statusName = '待维修'
            else if (item.status === 7) data.statusName = '待确认'
            else data.statusName = $get(statusMaps, item.status, '/')
          } else data.statusName = $get(statusMaps, item.status, '/')
          return Object.assign(item, data)
        })
        this[`count${tabIndex}`] = $get(res, 'data.data.count', 0)
        return loadRes
      }).catch(e => loadRes)
    },

    handleParams () {
      const { queryParam, tabIndex, $moment } = this
      const res = {}
      const params = { ...queryParam[tabIndex] }
      for (const key in params) {
        const item = params[key]
        if (key === 'createdTime' && item) res[key] = $moment(item).format('YYYY-MM-DD')
        else if (item) res[key] = item
        if (key === 'status' && res[key] && res[key].length > 1) {
          if (/0/.test(tabIndex)) res[key] = res[key].replace(/\,3|\,5|\,6|\,7|\,9/g, '')
          else if (/1/.test(tabIndex)) res[key] = res[key].replace(/\,3|\,5|\,7/g, '')
          else if (/2/.test(tabIndex)) res[key] = res[key].replace(/\,1|\,2|\,4|\,6|\,9|\,11/g, '')
        }
      }
      if (!res.status) res.status = statusFilter[tabIndex].value
      return res
    },

    checkPDF ({ id = -1, applyType = '申请单', sn = '', status = -1 }) {
      if (id === -1) return false

      this.modalTitle = applyType
      this.modalText = `${applyType.replace('单', '')}状态：${statusMaps[status]}`
      this.url = ''
      this.fileName = ''

      this.$toggleSending(1)
      this.$axios({
        url: `api/assetsApply/down/${id}`,
        responseType: 'arraybuffer',
        method: 'get',
        contentType: 'application/pdf;charset=utf-8'
      }).then(res => {
        if (!res.data.code) {
          const blob = new Blob([res.data], { type: 'application/pdf;charset=utf-8' })
          this.url = window.URL.createObjectURL(blob)
          this.fileName = `${applyType}_${sn}_${Date.now()}`
          this.showPDF = true
          this.$toggleSending()
        }
      }).catch(e => [])
    },

    clickExport (index) {
      this.showExport = true
    },

    async handleExport () {
      const { tabIndex, queryParam } = this
      this.$toggleSending(1)
      const name = ['申购', '申领', '报修'][tabIndex]
      const nowTime = Date.now()
      const param = { ...queryParam[tabIndex] }
      delete param.pageSize
      param.pageNum = -1
      const bool = await this.$exportFile({ url: `api/assetsApply/export`, param, fileName: `${name}记录报表_${nowTime}` })
      if (bool) this.showExport = false
      this.$toggleSending()
    },

    reset (index) {
      const { tempQueryParam, tabIndex } = this
      const value = { sn: undefined, createdTime: undefined, status: undefined }
      if (index < 2) Object.assign(value, { deptId: undefined, approverName: undefined })
      else Object.assign(value, { attr: undefined, location: undefined })
      Object.assign(tempQueryParam[tabIndex], value)
    },

    // 点击搜索
    handleSearch (index) {
      const { queryParam, refresh, setQueryParam, tempQueryParam } = this
      const value = tempQueryParam[index]
      const target = queryParam[index]
      if (index < 2) value.pageNum = 1
      setQueryParam({ target, value })
      refresh(index)
    },

    handlePage (pageNum = 1) {
      const { queryParam, tempQueryParam, refresh, tabIndex, setQueryParam } = this
      const values = { ...queryParam[tabIndex] }
      delete values.pageNum
      delete values.pageSize
      Object.assign(tempQueryParam, values)
      if (tabIndex < 3) setQueryParam({ target: queryParam[tabIndex], value: { pageNum }})
      refresh(tabIndex)
    },

    // 刷新表单
    refresh (index = -1) {
      if (index === -1) return false
      if (index < 3) {
        const table = this.$get(this.$refs, `table${index}.0`, {})
        table && table.refresh && table.refresh()
      } else this.getSettings(this.settingTabIndex)
    },

    // 获取审批数据
    async getSettings (index = -1) {
      if (index === -1) return false
      const type = ['申购', '申领', '报修'][index]
      const { $axios, $get, $clonedeep } = this
      this.$toggleSending(1)
      const list = await $axios.post('api/approvalSet/query', { pageNum: -1, type })
        .then(res => $get(res, 'data.data.dataList', []))
        .catch(e => [])
      const settingData = { status: '', list: [], deleteList: [], userData: { userId: undefined }}
      const statusItem = list.filter(i => /0|1/.test(i.status) && !i.userId)
      if (!statusItem.length) {
        list.some(i => {
          if (/0|1/.test(i.status)) {
            settingData.status = i.status
            return true
          }
        })
      } else settingData.status = statusItem[0].status
      settingData.list = $clonedeep(list)
      const personList = list.filter(i => i.userId)
      // .sort((a, b) => $moment(a.createdTime).isBefore(b.createdTime) ? 1 : -1)
      settingData.personList = personList
      if (index === 2 && personList[0]) settingData.userData = personList[0]
      Object.assign(this.settingData, settingData)
      this.oldSettingData = $clonedeep(settingData)
      this.$toggleSending()
    },

    // 点击删除
    handleDel (index = -1) {
      if (index === -1) return false
      const { settingData } = this
      settingData.personList.splice(index, 1)
    },

    // 添加/修改 审批人
    handleOk () {
      const { tempUserId, $message, settingData, tempIndex, settingTabIndex } = this
      $message.destroy()
      if (!tempUserId) return $message.error('请选择审批人')
      if (tempIndex !== -1) Object.assign(settingData.personList[tempIndex], { userId: tempUserId })
      else settingData.personList.push({ userId: tempUserId, type: ['申购', '申领', '报修'][settingTabIndex], status: settingData.status })
      this.showSelect = false
    },

    handleSelect (userId = undefined, targetIndex = -1) {
      this.tempUserId = userId
      this.tempDept = undefined
      this.tempIndex = targetIndex
      this.showSelect = true
    },

    // 更新数据
    async handleUpdate () {
      if (this.sending) return false
      this.$toggleSending(1)
      const { settingData, $message, settingTabIndex, oldSettingData, $get, $axios } = this
      $message.destroy()
      let msg = ''
      if (settingTabIndex < 2) {
        if (!settingData.status && !(/0/.test(settingData.status))) msg = '请选择审批类型'
        if (/1/.test(settingData.status) && !$get(settingData, 'personList.length')) msg = '请添加审批人'
      } else if (!$get(settingData, 'userData.userId')) msg = '请选择审批人'
      if (msg) {
        $message.error(msg)
        this.$toggleSending()
        return false
      }

      const newList = settingData.personList.filter(i => !i.id)
      const updateList = settingData.personList.filter(i => i.id)
      const statusItem = { type: ['申购', '申领', '报修'][settingTabIndex], status: settingData.status }
      if (!$get(settingData, 'personList.length') && /0/.test(settingData.status)) updateList.push(statusItem)
      if (!newList.length && !updateList.length && settingTabIndex < 2) updateList.push(statusItem)
      if (settingTabIndex === 2 && $get(oldSettingData, 'userData.userId') !== $get(settingData, 'userData.userId')) {
        let target = updateList
        if (!$get(oldSettingData, 'userData.userId')) target = newList
        target.push({ ...settingData.userData, type: '报修' })
      }
      if (updateList.length) { // 修改
        const param = updateList.map(({ isDelete, id, type, status, userId }) => ({ isDelete, type, status, userId }))
        await $axios.put('api/approvalSet/', param).catch(e => $message('修改失败，请稍后再试'))
      }
      // 新增
      if (newList.length) await $axios.post('api/approvalSet/', newList).catch(e => $message('新增失败，请稍后再试'))

      if (updateList.length || newList.length) $message.info('已更新')
      this.getSettings()
      this.$toggleSending()
    },

    // 点击取消重置数据
    handleReset () {
      Object.assign(this.settingData, this.oldSettingData)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="less" scoped>
.tabs-col {
  /deep/ .ant-tabs-tab-active.ant-tabs-tab {
    padding-bottom: 0;
  }
}
</style>
